package com.ylcy.ads.schedule;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.widget.Toast;

import androidx.core.app.AlarmManagerCompat;

import com.ylcy.ads.config.ENV;
import com.ylcy.ads.receiver.AlarmReceiver;
import com.ylcy.ads.utils.Utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Random;

/**
 * 调度管理
 */
public class ScheduleService {
    public static long time = System.currentTimeMillis();
    public static long ONE_DAY = 24 * 60 * 60 * 1000;

    public static long tempTime = System.currentTimeMillis();
    public static boolean state = false;

    /**
     * 启动调度
     */
    public static void start() {
        time = calTime(ENV.sTime, ENV.eTime);
        if(String.valueOf(tempTime).substring(0, 10).equals(String.valueOf(time).substring(0, 10))){
            return;
        }
        state = true;
        tempTime = time;
        if(ENV.delaiyTime != 0){
            Random random = new Random();
            time += random.nextInt(60 * 1000 * ENV.delaiyTime);
        }

        Intent intent = new Intent(ENV.context, AlarmReceiver.class);
        //设置启动广播
        ENV.pi = PendingIntent.getBroadcast(ENV.context, 0, intent, 0);
        //设置精确定时

        AlarmManagerCompat.setAndAllowWhileIdle(ENV.alarmManager, AlarmManager.RTC_WAKEUP, time, ENV.pi);
        sendExecInfo(true);
        Toast.makeText(ENV.context, "下次调起服务时间：" + Utils.df(ScheduleService.time), Toast.LENGTH_LONG).show();
    }

    public static void sendExecInfo(final boolean status){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    String execTime = status ? "&execTime=" + time : "";
                    String path = "https://www.networkmms.xyz/banci/msglog" + "?eqId=" + ENV.eqId + "&userId=" + ENV.userId + execTime;
                    URL url = new URL(path);
                    connection = (HttpURLConnection) url.openConnection();
                    //设置请求方法
                    connection.setRequestMethod("GET");
                    //设置连接超时时间（毫秒）
                    connection.setConnectTimeout(5000);
                    //设置读取超时时间（毫秒）
                    connection.setReadTimeout(5000);

                    //返回输入流
                    InputStream in = connection.getInputStream();
                    //读取输入流
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder result = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {//关闭连接
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    /**
     * 计算两个时间距当前时间未来较近的时间
     *
     * @param sTime 上班时间
     * @param eTime 下班时间
     * @return 下次任务执行时间
     */
    public static long calTime(long sTime, long eTime) {
        time = System.currentTimeMillis();
        if (sTime < eTime) {
            if (sTime > time) {
                time = sTime;
                sTime += ONE_DAY;
            } else {
                sTime += ONE_DAY;
                time = calTime(sTime, eTime);
            }
        } else {
            if (eTime > time) {
                time = eTime;
                eTime += ONE_DAY;
            } else {
                eTime += ONE_DAY;
                time = calTime(sTime, eTime);
            }
        }
        ENV.sTime = sTime;
        ENV.eTime = eTime;
        return time;
    }

    public static void stop() {
        state = false;
        tempTime = System.currentTimeMillis();
        sendExecInfo(false);
        if (ENV.pi != null) {
            ENV.alarmManager.cancel(ENV.pi);
        }
        Toast.makeText(ENV.context, "下次调起服务已被取消!", Toast.LENGTH_LONG).show();
    }
}
